import React, { useState } from "react";
import { View, StyleSheet, Dimensions, Text, TextInput, Image } from "react-native";
import shajs from "sha.js"
import { Button, Dialog } from "@rneui/themed";
import ImportMnemonicList from './components/ImportMnemonicList';
import MenuModal from './components/MenuModal';
import ReplaceModal from './components/ReplaceModal';
import Loading from "@/components/LoadingModal";
import LockScreenSet from '@/components/LockScreenSet'
import CommonContext from '@/utils/createContext'
import { BIPSigner } from '@/models/BIPSigner'
import api from "@/request/api";
import IconNavBar from '@/components/IconNavBar'
import { sectokenCommonCenterWhiteProps } from '@/config/navigatorProps'
import { setObjectValue } from '@/utils/deviceStorage'
import InputImg from '@/assets/imgs/input.png'

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const VerifyMnemonic = (props) => {

    const [inputMnemonicList, setInputMnemonicList] = useState([])
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [isInputError, setIsInputError] = useState(false)
    const [inputValue, setInputValue] = useState('');
    const [index, setIndex] = useState(0);
    const [checkedIndex, setCheckedIndex] = useState();
    const [menuVisible, setMenuVisible] = useState(false);
    const [replaceVisible, setReplaceVisible] = useState(false);
    const [dialogVisible1, setDialogVisible1] = useState(false);
    const [dialogVisible2, setDialogVisible2] = useState(false);
    const [lockVisible, setLockVisible] = useState(false)

    const checkMnemonic = () => {
        try {
            const signer = new BIPSigner()
            let mnemonicStr = inputMnemonicList.join(' ')
            let result = signer.validateMnemonic(mnemonicStr)
            if (result) {
                setDialogVisible1(true)
            } else {
                setIsInputError(true)
            }
        } catch (error) {
            setIsInputError(true)
        }
    }

    const handlePressConfirm = () => {
        setLoadingVisible(true)
        let mnemonicStr = inputMnemonicList.join(' ')
        var skdt = shajs('sha256').update(mnemonicStr).digest('hex')
        api.words_register(skdt).then(res => {
            setLoadingVisible(false)
            setDialogVisible2(true)
            setObjectValue("token", res.token)
        }).catch(() => {
            setLoadingVisible(false)
        })
        setDialogVisible1(false)
    }

    const handlePressNextWord = () => {
        if (inputValue) {
            if (index <= 11) {
                let arr = inputMnemonicList
                arr[index] = inputValue
                setInputMnemonicList(arr)
                setInputValue('')
                setIndex(index + 1)
                if (index == 11) {
                    checkMnemonic()
                }
            }
        }
    }

    const handlePressChange = (value) => {
        if (typeof (checkedIndex) === 'number') {
            if (value) {
                inputMnemonicList.splice(checkedIndex, 1, value)
                setReplaceVisible(false)
            } else {
                inputMnemonicList.splice(checkedIndex, 1)
                let count = index - 1
                setIndex(count)
            }
            setInputMnemonicList([...inputMnemonicList])
        }
        setMenuVisible(false)
        if (isInputError) {
            setIsInputError(false)
        }
    }

    const handlePressReplace = () => {
        setMenuVisible(false)
        setReplaceVisible(true)
    }

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const navigatToNext = () => {
        props.navigation.navigate('main')
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} handlePressLeft={handlePressLeft}
                {...sectokenCommonCenterWhiteProps}
                {...{ title: '验证助记词', backgroundColor: '#5A72EC', barStyle: 'light-content' }} />
            <View style={{ flex: 1 }}>
                {inputMnemonicList && inputMnemonicList.length > 0 ? <View>
                    <View style={{ width: width, height: 48 * ratio, backgroundColor: isInputError ? '#FFCD06' : '#F6F6F9', justifyContent: 'center', alignItems: 'center' }}>
                        {isInputError && <Text style={styles.title2}>助记词有误！</Text>}
                    </View>
                    <View style={{ alignItems: 'center' }}>
                        <Text style={{ ...styles.title1, marginTop: 7 * ratio }}>输入你的助记词</Text>
                    </View>
                    <View style={styles.mnemonic}>
                        <CommonContext.Provider value={{ inputMnemonicList, setCheckedIndex, setModalVisible: setMenuVisible }}>
                            <ImportMnemonicList />
                        </CommonContext.Provider>
                    </View>
                </View> :
                    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                        <Image source={InputImg} style={{ width: 131 * ratio, height: 131 * ratio }} />
                        <Text style={{ ...styles.title1, marginTop: 15 * ratio }}>输入你的助记词</Text>
                    </View>}
            </View>
            <View style={styles.content}>
                <View style={{ flex: 6, justifyContent: 'center', alignItems: 'center' }}>
                    <TextInput
                        style={styles.content_input}
                        value={inputValue}
                        placeholder='请输入你的第一个助记词'
                        onChangeText={(value) => setInputValue(value)} />
                </View>
                <View style={{ flex: 2, justifyContent: 'center', alignItems: 'flex-start' }}>
                    <Button onPress={handlePressNextWord} type="clear">
                        <Text style={styles.content_button_title}>下一个单词</Text>
                    </Button>
                </View>
            </View>
            <CommonContext.Provider value={{ modalVisible: menuVisible, setModalVisible: setMenuVisible, handlePressReplace, handlePressChange }}>
                <MenuModal />
            </CommonContext.Provider>
            <CommonContext.Provider value={{ modalVisible: replaceVisible, setModalVisible: setReplaceVisible, handlePressChange }}>
                <ReplaceModal />
            </CommonContext.Provider>
            {lockVisible && <CommonContext.Provider value={{ modalVisible: lockVisible, setModalVisible: setLockVisible, isReset: false, navigatToNext, isCreate: false, mnemonicStr: inputMnemonicList.join(' ') }}>
                <LockScreenSet />
            </CommonContext.Provider>}
            <Dialog
                isVisible={dialogVisible1}
                overlayStyle={{ ...styles.dialogContent, height: 160 * ratio }}
                onBackdropPress={() => { setDialogVisible1(false) }}
            >
                <View style={{ flex: 1, alignItems: 'center' }}>
                    <Text style={{ ...styles.title1, width: 200 * ratio, color: '#646464', marginTop: 14 * ratio }}>
                        Mnemonic verification succeeded, Exit?
                    </Text>
                    <View style={styles.divider1}></View>
                    <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center' }}>
                        <Button onPress={() => { setDialogVisible1(false) }} type="clear">
                            <Text style={{ ...styles.title3, color: '#646464' }}>Cancel</Text>
                        </Button>
                        <View style={styles.divider2}></View>
                        <Button onPress={handlePressConfirm} type="clear">
                            <Text style={styles.title3}>Confirm</Text>
                        </Button>
                    </View>
                </View>
            </Dialog>
            <Dialog
                isVisible={dialogVisible2}
                overlayStyle={styles.dialogContent}
                onBackdropPress={() => { setDialogVisible2(false) }}
            >
                <View style={{ flex: 1, alignItems: 'center' }}>
                    <Text style={{ ...styles.title1, color: '#646464', marginTop: 10 * ratio }}>
                        exit successful
                    </Text>
                    <View style={styles.divider1}></View>
                    <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                        <Button onPress={() => { setLockVisible(true) }} type="clear">
                            <Text style={styles.title4}>Confirm</Text>
                        </Button>
                    </View>
                </View>
            </Dialog>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View >
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F6F6F9'
    },
    mnemonic: {
        marginTop: 19 * ratio,
        marginLeft: 15 * ratio
    },
    content: {
        width: width,
        height: 60 * ratio,
        flexDirection: 'row',
        backgroundColor: '#FFFFFF'
    },
    content_input: {
        width: 244 * ratio,
        height: 39 * ratio,
        backgroundColor: '#DDDDDD',
        borderRadius: 17,
        borderColor: '#E9E9E9',
        borderWidth: 1,
        paddingLeft: 21 * ratio
    },
    content_button_title: {
        fontSize: 12,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#2C2C2C',
        lineHeight: 18
    },
    title1: {
        fontSize: 18,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#898989',
        lineHeight: 24
    },
    title2: {
        fontSize: 17,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FFFFFF',
        lineHeight: 22
    },
    title3: {
        fontSize: 13,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FF6600',
        lineHeight: 17
    },
    title4: {
        fontSize: 14,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#FF6600',
        lineHeight: 19
    },
    dialogContent: {
        width: 324 * ratio,
        height: 134 * ratio,
        borderRadius: 5
    },
    divider1: {
        width: 324 * ratio,
        height: 0,
        borderWidth: 1,
        borderColor: '#E4E4E4',
        marginTop: 36 * ratio
    },
    divider2: {
        width: 0,
        height: 38 * ratio,
        borderWidth: 1,
        borderColor: '#E4E4E4'
    }
})
export default VerifyMnemonic